#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2018/10/23 20:25
# @Author  : Tang Yang
# @Site    : 
# @File    : main.py
import matplotlib
matplotlib.use('agg')
from src.server import ShelfServer
from src.utils.context import Context
from src.utils.custom_exception import *
import cv2
import time


def image_processor(imgs: list, runtime_context):
    """
    接口程序
    :param runtime_context: 运行时环境，包括所有需要的模型
    :param imgs: 所有需要检测的图片(RGB三通道)，大于 1 张表示需要拼接
    :return: json形式的检测结果
              如果需要拼接，返回拼接好的图片，否则返回检测时的图片
              返回绘制好 box 的图片
    :raises:
            ValueError: 图片为空
            DetectionError: 检测过程中出错
            StitchingError: 拼接出错
            ConfigParseError: config.xml 文件解析错误
    """
    ss = ShelfServer(imgs, runtime_context)
    return ss.get_response(), ss.get_img(), ss.get_img_after_draw()


def test():
    img_names = [r"D:/workspace/stitch_img/imgs/caffe_1/1.jpg",
                 "D:/workspace/stitch_img/imgs/caffe_1/2.jpg",
                 "D:/workspace/stitch_img/imgs/caffe_1/3.jpg"]
    all_imgs = []
    for name in img_names:
        img = cv2.imread(name)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        all_imgs.append(img)

    try:
        start = time.clock()
        runtime_context = Context(r"D:\workspace\Shelf-product-identification\config.xml")
        end = time.clock()
        print("Load model: ", end - start)
        response, img, draw = image_processor(all_imgs, runtime_context)
        finish = time.clock()
        print("Total time: ", finish - start)
        print(response)
        cv2.imshow("img", draw)
        cv2.waitKey()
    except FileNotFoundError:
        print("config.xml not found")
    except ConfigParseError:
        print("config file parse error")
    except ValueError:
        print("image list is empty")
    except DetectionError:
        print("Error Occurred during the Detection")
    except StitchingError:
        print("Error Occurred during the Stitching")


# 测试
if __name__ == '__main__':
    test()
